//
//  UIColor+Extension.swift
//  EasyDana
//
//  Created by mac on 2024/10/9.
//

import Foundation
import UIKit
extension UIColor {
    
    static func color(with red: Int, green: Int, blue: Int, alpha: CGFloat = 1) -> UIColor {
        return self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
    }
    
    static func hex(with hex: String) -> UIColor {
        var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines)
        if cString.count < 6 { return UIColor.black }

        let index = cString.index(cString.endIndex, offsetBy: -6)
        let subString = cString[index...]

        if cString.hasPrefix("0X") {
            cString = String(subString)
        }
        if cString.hasPrefix("#") {
            cString = String(subString)
        }

        if cString.count != 6 {
            return UIColor.black
        }

        var range = NSRange(location: 0, length: 2)
        let rString = (cString as NSString).substring(with: range)
        range.location = 2
        let gString = (cString as NSString).substring(with: range)
        range.location = 4
        let bString = (cString as NSString).substring(with: range)

        var r: UInt64 = 0x0
        var g: UInt64 = 0x0
        var b: UInt64 = 0x0

        Scanner(string: rString).scanHexInt64(&r)
        Scanner(string: gString).scanHexInt64(&g)
        Scanner(string: bString).scanHexInt64(&b)

        return UIColor.color(with: Int(r), green: Int(g), blue: Int(b))
    }
    
    var image: UIImage {
        let size = CGSize(width: 1, height: 1)
        let renderer = UIGraphicsImageRenderer(size: size)
        let image = renderer.image {  context in
            self.setFill()
            context.fill(CGRect(origin: CGPoint.zero, size: size))
        }
        return image
    }
}
